#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
import logging
import time

from logger import logger
from odl_handler import NodeConfig, ODLConfig, ODLHandler

if __name__ == '__main__':
    logger = logger('example1', 'logs/example1.log', logging.DEBUG, logging.DEBUG)

    # 创建ODLHandler实例
    # ================================================================================
    odl = ODLConfig(host='192.168.171.15')
    node = NodeConfig(host='192.168.171.76')
    h = ODLHandler(odl, node)

    # 在ODL服务器上创建netconf连接器
    # ================================================================================
    if h.create_connector():
        logger.info(f'created netconf connector for {node.Host}')
    else:
        logger.error(f'failed to create netconf connector for {node.Host}')

    # 等待连接器状态变成connected (服务器和设备建立连接)
    # ================================================================================
    for _ in range(10):
        if h.check_connector_connection_status():
            logger.info('netconf connector is connected')
            break
        logger.warning('waiting for connector to connect...')
        time.sleep(5)
    else:
        logger.error('netconf connector failed to connect')

    # 获取或修改交换机的配置
    # opendaylight安装`odl-mdsal-apidocs`模块后，可以通过浏览器API文档: http://<controller-ip>:8181/apidoc/explorer/index.html
    # ================================================================================
    # 全局 QinQ
    result = h.get(yang_pth='readylinks-rlos:configure/vlan-vpn')
    global_qinq_enabled = result.get('readylinks-rlos:vlan-vpn').get('enabled')
    logger.info(f'global QinQ enabled: {global_qinq_enabled}')
    if global_qinq_enabled:
        if h.put(yang_pth='readylinks-rlos:configure/vlan-vpn', json={"vlan-vpn": {"enabled": True}}):
            logger.info('set global QinQ enabled to True')
        else:
            raise Exception('failed to set global QinQ to enabled')

    # 某个端口添加QinQ条目
    if h.put(f'readylinks-rlos:ports/port={14}/vlan-vpn', json={
        "vlan-vpn": {
            "enabled": True,
            "qinq": [
                {
                    "old-vid": 1022,  # inner vlan id
                    "old-low-vid": 1022,
                    "old-high-vid": 1022,
                    "new-inner-vid": 0,  # 0 means no convertion inner vlan id
                    "new-vid": 33,  # outer vlan id
                    "priority": 4
                }
            ]
        }
    }):
        logger.info('added QinQ entry to port14')
    else:
        raise Exception('failed to add QinQ entry to port14')

    # ...

    # 删除连接器
    # ================================================================================
    # if h.delete_connector():
    #     logger.info(f'deleted netconf connector for {node.Host}')
    # else:
    #     logger.error(f'failed to delete netconf connector for {node.Host}')
